using UnityEngine;

namespace RedNoteModule
{
    public interface IRedNoteVisualComponent
    {
        bool IsDestroyed { get; }

        string RedNoteKey { get; }

        public void RedNoteValueChange(bool isActive);
    }

    public class RedNoteVisualComponent : MonoBehaviour, IRedNoteVisualComponent
    {
        [SerializeField] private Transform m_redNoteVisual;

        private Vector3 m_originalScale = Vector3.one;
        private bool m_state = false;
        private bool m_inited = false;

        private string m_curRedNoteKey = string.Empty;

        protected virtual void Awake()
        {
            if (!m_inited)
            {
                SetRedNoteValueInner(false);
            }
        }

        protected virtual void OnDestroy()
        {
            IsDestroyed = true;
            ClearRedNoteType();
        }

        private void SetRedNoteValueInner(bool value)
        {
            CheckInit();

            m_state = value;
            if (m_redNoteVisual != null)
            {
                m_redNoteVisual.localScale = m_state ? m_originalScale : Vector3.zero;
            }
        }

        private void CheckInit()
        {
            if (m_inited)
            {
                return;
            }

            m_originalScale = m_redNoteVisual.localScale;
            m_inited = true;
        }

        private void AddChgListener(string key)
        {
            m_curRedNoteKey = key;
            RedNoteMgr.Instance.AddRedNoteChangeListener(m_curRedNoteKey, this);
        }

        private void RemoveChgListener()
        {
            if (!string.IsNullOrEmpty(m_curRedNoteKey))
            {
                RedNoteMgr.Instance.RemoveRedNoteChangeListener(m_curRedNoteKey, this);
            }

            m_curRedNoteKey = string.Empty;
        }

        public void SetRedNoteValue(bool value)
        {
            if (!string.IsNullOrEmpty(m_curRedNoteKey))
            {
                Debug.LogWarning("试图对已经指定了类型的红点视觉组件直接修改值");
                return;
            }

            SetRedNoteValueInner(value);
        }

        public void SetRedNoteType(string key)
        {
            AddChgListener(key);
        }

        public void SetRedNoteType(RedNoteType redNoteType)
        {
            AddChgListener(redNoteType.ToString());
        }

        public void ClearRedNoteType(bool toState = false)
        {
            RemoveChgListener();
            SetRedNoteValueInner(toState);
        }

        #region override

        public bool IsDestroyed { get; private set; }
        public string RedNoteKey => m_curRedNoteKey;

        public void RedNoteValueChange(bool isActive)
        {
            SetRedNoteValueInner(isActive);
        }

        #endregion
    }
}